package cn.itsource.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Slf4j
@Component
public class LoginGlobalFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("=========进入全局过滤器 LoginGlobalFilter===============");
        // 1. 获取tonken
        HttpHeaders headers = exchange.getRequest().getHeaders();
        List<String> token = headers.get("token");
        // 2. 判断是否存在
        if(token==null || token.isEmpty()){
            log.info("=========token 不存在 ===============");
            // 2.2 不存在 拦截请求 ，后面的过滤器都不执行
            // 设置响应码
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            // 消息处理已完成，允许执行任何清理或处理结束任务
            return response.setComplete();

        }
            // 2.1 存在请求放行，执行下一个过滤器
            return chain.filter(exchange);

    }

    @Override
    public int getOrder() {
        // 全局的还是要先一些
        return Ordered.HIGHEST_PRECEDENCE;
    }
}
